import request from "@/utils/request";

function handleResponse(response) {
  if (response?.data?.error) {
    console.error("RTMP API Error:", response.data.error);
    throw new Error(response.data.error.message || 'RTMP API 请求失败');
  }
  if ('result' in response?.data) {
    return response.data.result;
  }
  console.error("Unexpected RTMP API response format:", response?.data);
  throw new Error('RTMP API 响应格式错误或非预期结果');
}

export async function getRTMPConfig() {
  try {
    const response = await request.post('/v1/jsonrpc2', {
      id: `rtmp-get-config-${Date.now()}`,
      method: 'rtmp.getConfig',
      params: {}
    });
    return handleResponse(response);
  } catch (error) {
    console.error("获取RTMP配置失败:", error);
    throw error instanceof Error ? error : new Error('获取RTMP配置失败');
  }
}

export async function setRTMPConfig(config) {
  try {
    const response = await request.post('/v1/jsonrpc2', {
      id: `rtmp-set-config-${Date.now()}`,
      method: 'rtmp.setConfig',
      params: config
    });
    return handleResponse(response);
  } catch (error) {
    console.error("设置RTMP配置失败:", error);
    throw error instanceof Error ? error : new Error('设置RTMP配置失败');
  }
}

export function validateRtmpUrl(url) {
  if (!url || typeof url !== 'string') return false;
  return /^rtmps?:\/\//i.test(url);
}

export async function getRTMPStatus() {
  try {
    const response = await request.post('/v1/jsonrpc2', {
      id: `rtmp-get-status-${Date.now()}`,
      method: 'rtmp.getStatus',
      params: {}
    });
    return handleResponse(response);
  } catch (error) {
    console.error("获取RTMP状态失败:", error);
    throw error instanceof Error ? error : new Error('获取RTMP状态失败');
  }
}
